// 第二步：创建PostService
package com.badboy.service;

import com.badboy.mapper.PostsMapper;
import com.badboy.entity.Posts;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.badboy.util.MyBatisUtil;

import java.util.List;

public class PostService {
    private final SqlSessionFactory sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();
    private PostsMapper postsMapper;
    public List<Posts> getPosts(Integer forumId, String sortType, int page, int pageSize) {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            PostsMapper mapper = session.getMapper(PostsMapper.class);
            int offset = (page - 1) * pageSize;
            return mapper.selectPosts(forumId, sortType, pageSize, offset);
        }
    }

    public int countPosts(int forumId) {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            PostsMapper mapper = session.getMapper(PostsMapper.class);
            return mapper.countByForum(forumId);
        }
    }


    public Posts getPostWithManagementInfo(Long postId) {
        return postsMapper.selectPostWithManagementInfo(postId);
    }
    //创建查询方法
    public List<Posts> searchPostsByContent(Integer forumId, String keyword, String sortType) {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            PostsMapper mapper = session.getMapper(PostsMapper.class);
            return mapper.searchPostsByContent(forumId, keyword, sortType);
        }
    }
}